package com.sky.filters;

import com.sky.config.AuthProperties;
import com.sky.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request
        ServerHttpRequest request = exchange.getRequest();
        log.info("Received request: {} {}", request.getMethod(), request.getURI());
        
        // 2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())) {
            // 无需拦截，直接放行
            log.info("Path is in exclude list, allowing request to pass through");
            Mono<Void> result = chain.filter(exchange);
            log.info("Chain filter completed for excluded path");
            return result;
        }
        
        log.info("Path requires authentication, checking token");
        // 3.获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        // 如果没有token，直接拒绝
        if (token == null || token.isEmpty()) {
            log.warn("No token provided in request");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        
        // 4.校验并解析token
        Long empId = null;
        try {
            empId = jwtTool.parseToken(token);
        } catch (Exception e) {
            log.warn("Token validation failed: ", e);
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5.传递用户信息
        String userInfo = empId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("employeeId", userInfo))
                .build();
        // 6.放行
        log.info("Token validated, forwarding request with employeeId: {}", userInfo);
        return chain.filter(swe);
    }
    
    private boolean isExclude(String antPath) {
        log.info("Checking exclude path: {}", antPath);
        for (String pathPattern : authProperties.getExcludePaths()) {
            boolean match = antPathMatcher.match(pathPattern, antPath);
            log.info("Matching {} with {}: {}", pathPattern, antPath, match);
            if (match) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public int getOrder() {
        return 0;
    }
}